import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { ChatSession, ChatSessionDocument } from '../database/schemas/chat-session.schema';

export interface CreateSessionDto {
  title: string;
  model: string;
  messages?: Array<{
    role: 'user' | 'assistant';
    content: string;
    timestamp: Date;
  }>;
}

export interface UpdateSessionDto {
  title?: string;
  messages?: Array<{
    role: 'user' | 'assistant';
    content: string;
    timestamp: Date;
  }>;
}

@Injectable()
export class ChatSessionService {
  constructor(
    @InjectModel(ChatSession.name)
    private chatSessionModel: Model<ChatSessionDocument>,
  ) {}

  /**
   * 创建新会话
   */
  async create(createSessionDto: CreateSessionDto): Promise<ChatSessionDocument> {
    const session = new this.chatSessionModel({
      ...createSessionDto,
      messages: createSessionDto.messages || [],
    });
    return session.save();
  }

  /**
   * 获取所有会话
   */
  async findAll(): Promise<ChatSessionDocument[]> {
    return this.chatSessionModel
      .find()
      .sort({ updatedAt: -1 })
      .exec();
  }

  /**
   * 根据 ID 获取会话
   */
  async findById(id: string): Promise<ChatSessionDocument | null> {
    return this.chatSessionModel.findById(id).exec();
  }

  /**
   * 更新会话
   */
  async update(
    id: string,
    updateSessionDto: UpdateSessionDto,
  ): Promise<ChatSessionDocument | null> {
    return this.chatSessionModel
      .findByIdAndUpdate(id, { ...updateSessionDto, updatedAt: new Date() }, { new: true })
      .exec();
  }

  /**
   * 添加消息到会话
   */
  async addMessage(
    id: string,
    message: { role: 'user' | 'assistant'; content: string; timestamp: Date },
  ): Promise<ChatSessionDocument | null> {
    try {
      const session = await this.findById(id);
      if (!session) {
        console.error(`❌ Session not found: ${id}`);
        return null;
      }

      // 确保消息对象符合 Schema 定义
      const messageToSave = {
        role: message.role,
        content: message.content,
        timestamp: message.timestamp || new Date(),
      };

      session.messages.push(messageToSave);
      session.updatedAt = new Date();

      // 如果这是第一条消息，更新标题
      if (session.messages.length === 1 && message.role === 'user') {
        session.title = message.content.slice(0, 50) + (message.content.length > 50 ? '...' : '');
      }

      const saved = await session.save();
      console.log(`✅ Message saved to session ${id}, total messages: ${saved.messages.length}`);
      console.log(`   Message: role=${messageToSave.role}, content length=${messageToSave.content.length}`);
      return saved;
    } catch (error) {
      console.error(`❌ Error in addMessage for session ${id}:`, error);
      throw error;
    }
  }

  /**
   * 删除会话
   */
  async delete(id: string): Promise<boolean> {
    const result = await this.chatSessionModel.findByIdAndDelete(id).exec();
    return !!result;
  }
}

